var db = require("../util/DataBase.js");

var blackUserService = require("../service/black_user.js");

var topicService = {
  getFollowUserTopic(topicId, success, error) {
    db.query("SELECT `id`, `user_id`, `topic_id` FROM `follow_user_topic` WHERE `topic_id` = ?", [
      topicId
    ], function (err, results) {
      if(err) {
        error && error("获取话题下用户失败");
      } else {
        success && success(results);
      }
    })
  },
  getFollowTopic(userId, success, error) {

    var values = [
      userId
    ];

    db.query("SELECT `id`, `user_id`, `topic_id` FROM `follow_user_topic` WHERE `user_id` = ?", values, function(err, results) {

        if(err)
        {
            error && error();
            return;
        }

        success(results);

    });

  },
  getArticleList(userId, topicId, len, startPublishId, sort, knowledge, success, error) {

    blackUserService.getBlockUserList(userId, (results) => {

      var values = [
        topicId * 1,
        startPublishId * 1,
        len * 1
      ]

      if(values[0] == -1) {
        values.shift();
      }

      var sqlQuery = [
        "SELECT `article_id`, count(article_in_topic.id) as `in_topic` FROM `article_in_topic`, article WHERE "
      ];

      if(results.length > 0) {
        sqlQuery.push(" article.user_id NOT IN (" +
          results.map((blockUser) => {
            return blockUser.block_user_id;
          })
        + ") AND ");
      }

      if(values.length == 3) {
        sqlQuery.push(" `topic_id` = ? AND" );
        finalJob();
      }
      else {
        topicService.getFollowTopic(userId, (userFollowList) => {
          var userFollowTopicIdList = [];

          for(var i = 0, l = userFollowList.length; i < l; ++ i) {
            userFollowTopic = userFollowList[i];
            userFollowTopicIdList.push(userFollowTopic.topic_id);
          }

          sqlQuery.push(" `topic_id` IN (" + userFollowTopicIdList.join(",") + ") AND ");

          finalJob()

        }, () => {
          error && error();
        });
      }

      function finalJob() {

        if(knowledge == 1) {
          sqlQuery.push(" article.knowledge = 1 AND ");
        }

        sqlQuery.push(" article.id = `article_id` AND article.publish_id " + ( sort === "asc" ? "<" : ">") + " ? GROUP BY `article_id` ORDER BY article.publish_id DESC LIMIT ?");

        db.query(sqlQuery.join(""), values, function(err, results) {

            if(err)
            {
                error && error();
                return;
            }

            success(results);

        });

      };

    }, () => {
      error && error();
    });


  },
  removeAllFollow(userId, success, error) {

    var values = [
      userId
    ];

    db.query("DELETE FROM `follow_user_topic` WHERE `user_id` = ?", values, function(err, results) {

      if(err)
      {
        error && error(err);
      }
      else
      {
        success && success();
      }

    });

  }
};

module.exports = topicService;
